import { Component, Input, OnInit, OnDestroy, ViewChild, Renderer2, ElementRef } from '@angular/core';
import { NavParams, ModalController } from '@ionic/angular';
import { VgAPI } from 'videogular2/core';
// import { Screenshot } from '@ionic-native/screenshot/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { RoomEchartsService } from '@services/echarts/room.echarts.service';
import { DataService } from '@services/data.service';
import { CacheService } from '@services/cache.service';
import { MyNoteService } from '@services/myNote.service';
import { DatePipe } from '@angular/common';
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';

export interface IMedia {
    src: string;
}

declare var window;
declare var screen;
@Component({
    selector: 'device-video',
    templateUrl: './device-video.html',
    styleUrls: ['device-video.scss']
})
export class DeviceVideoModal implements OnInit, OnDestroy {

    @Input() config;
    // @ViewChild('videoView') deviceVideoListView: Scroll;

    api: VgAPI;
    options;
    showTool = true;
    projectId;
    deviceType;

    paramsPitch = 0;
    pitch = 0;
    currentItem: IMedia = {
        src: '',
    };

    isOnline;   // 摄像头在线状态
    refreshInterval;

    constructor(private params: NavParams,
        // private viewCtrl: ViewController,
        private echart: RoomEchartsService,
        private dataservice: DataService,
        private cacheservice: CacheService,
        // private screenshot: Screenshot,
        private myNote: MyNoteService,
        private statusBar: StatusBar,
        private modalCtrl: ModalController,
        private orientation: ScreenOrientation,
        private renderer: Renderer2,
        private el: ElementRef
    ) {
        console.log('config', this.params.get('config'));
        this.config = this.params.get('config');
        this.projectId = this.cacheservice.currentProject.projectId;
        this.statusBar.hide();
    }

    ngOnInit() {
        if (window.cordova) {
            screen.orientation.lock('landscape');
        }
        this.getVideoUrl(this.pitch, null);
        console.log(this.config)
        this.getCameraChart(this.config.deviceVideoList[0].cameraId);
        console.log('在线状态', this.config.deviceVideoList[0].isOnline)
        this.isOnline = this.config.deviceVideoList[0].isOnline;
        // this.getCameraStatus(this.config.deviceVideoList[0].cameraId)
        // this.getImportantDeviceTypeByArea();
    }

    ionViewWillEnter() {
    }

    ionViewWillLeave() {
    }

    onPlayerReady(api: VgAPI) {
        this.api = api;
        this.api.getDefaultMedia().subscriptions.loadedMetadata.subscribe(res => {
            console.log('视频加载成功', res)
            this.playVideo();
        });
        this.api.getDefaultMedia().subscriptions.error.subscribe(
            (error) => {
                console.log('视频加载失败')
                if (this.currentItem && this.currentItem.src) {
                    this.checkUrl(this.currentItem.src);
                }
            }
        );

        this.api.getDefaultMedia().subscriptions.error.subscribe(
            (error) => {
                console.log('视频播放失败', this.currentItem)
                if (this.currentItem && this.currentItem.src) {
                    this.checkUrl(this.currentItem.src);
                }
            }
        );
    }

    playVideo() {
        this.api.play();
    }

    closeModal() {
        this.modalCtrl.dismiss();
    }

    showEcharts(data) {
        this.options = this.echart.showRoomParamsChart(data);
        console.log(this.options)
    }

    refreshVideo(e) {
        console.log('刷新视频', e.path[0]);
        const ele = this.el.nativeElement.querySelector('.refresh');
        this.renderer.setStyle(ele, 'animation', 'rotating 1.2s linear infinite');
        this.getVideoUrl(this.pitch, ele);
        this.getCameraChart(this.config.deviceVideoList[this.pitch].cameraId)
    }

    // 截屏
    toPhoto() {
        // const name = 'myscreenshot' + new Date().getTime() + '.jpg';
        // this.screenshot.save('jpg', 80, name).then((data) => {
        //     console.log(data);
        //     this.myNote.MyNotice('截图成功');
        // }, (err) => {
        //     console.log(err);
        //     this.myNote.MyNotice('截图失败');
        // });
    }

    choose(index) {
        this.pitch = index;
        console.log('摄像头Id', this.config.deviceVideoList[this.pitch]);
        this.getVideoUrl(this.pitch, null);
        this.getCameraChart(this.config.deviceVideoList[this.pitch].cameraId)
    }

    scrollVideo() {
        let interval;
        let count; count = 0;
        interval = setInterval(() => {
            count++;
            if (count >= 20) {
                clearInterval(interval);
            }
        }, 10);
    }

    getVideoUrl(index, ele?) {
        this.currentItem = { src: '' };
        this.dataservice.getRoomVideoList(this.config.areaId).subscribe(res => {
            console.log('摄像头列表', res.data.datas, this.config)
            if (res.success) {
                if (res.data) {
                    const cameraOne = [];
                    for (let i = 0; i < res.data.datas.length; i++) {
                        if (res.data.datas[i].position === 1) {
                            if (res.data.datas[i].cameraId === this.config.deviceVideoList[index].cameraId) {
                                cameraOne.push(res.data.datas[i])
                            }
                        }
                    }
                    if (ele) {
                        setTimeout(() => {
                            console.log('刷新成功', cameraOne)
                            this.currentItem = { src: cameraOne[index].liveUrl };
                            this.renderer.removeStyle(ele, 'animation')
                            if (!this.currentItem.src) {
                                this.getOtherUrl(this.config.deviceVideoList[index].cameraId);
                            }
                        }, 2000);
                    } else {
                        console.log('视频获取成功', cameraOne)
                        this.currentItem = { src: cameraOne[index].liveUrl };
                        if (!this.currentItem.src) {
                            this.getOtherUrl(this.config.deviceVideoList[index].cameraId)
                        }
                    }
                }
            }
        });
    }

    // 如果没有直播地址则调取另一个接口
    getOtherUrl(cameraId) {
        this.dataservice.getRoomVideoUrl(cameraId).subscribe(res => {
            if (res.success) {
                this.currentItem = { src: res.data };
            }
        });
    }

    // 一秒钟验证一下url有没有资源
    checkUrl(url) {
        this.currentItem = { src: '' };
        setTimeout(() => {
            this.currentItem = { src: url };
        }, 1000);
    }


    getImportantDeviceTypeByArea() {
        this.dataservice.getImportantDeviceTypeByArea(this.config.areaId).subscribe(res => {
            console.log(res)
            if (res && res.data) {
                this.deviceType = res.data.importDevices;
            }
        });
    }

    hideOrShowTool() {
        this.showTool = !this.showTool;
    }

    selectParams() {
        this.getCameraChart(this.config.deviceVideoList[this.pitch].cameraId);
    }

    ngOnDestroy() {
        if (window.cordova) {
            screen.orientation.lock('portrait');
        }
        this.statusBar.show();
        this.statusBar.overlaysWebView(true);
    }

    getCameraChart(cameraId) {
        const date = new Date();
        const toDay = this.formatDate(date, 'yyyy-MM-dd 00:00:00');
        const nextday = + date + 1000 * 60 * 60 * 24;
        const nextDay = this.formatDate(new Date(nextday), 'yyyy-MM-dd 00:00:00');
        const searchTime = [toDay, nextDay]
        console.log(searchTime);
        this.dataservice.getCameraParamCurve(cameraId, 4, [1], searchTime, 24).subscribe(res => {
            if (res.success === true) {
                res.data.charts = [];
                // for (const data of res.data) {
                res.data.parameterName = "通讯状态";
                res.data.unit = "";
                res.data.max = 1;
                res.data.min = 0;
                res.data.point = [];
                for (const data of res.data.data) {
                    res.data.point.push({ x: data.triggeringTime, y: data.val });
                }
                // }
                res.data.charts[0] = res.data;
                console.log('通讯状态历史曲线', res.data.charts);
                this.showEcharts(res.data.charts);
            }
        }, (error: any) => {
            console.log('获取折线图数据异常', error);
        });
    }

    formatDate(date, fmt) {
        const o = {
            'M+': date.getMonth() + 1,                   // 月份
            'd+': date.getDate(),                        // 日
            'h+': date.getHours(),                       // 小时
            'm+': date.getMinutes(),                     // 分
            's+': date.getSeconds(),                     // 秒
            'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
            'S': date.getMilliseconds()                  // 毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (const k in o) {
            if (new RegExp('(' + k + ')').test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
            }
        }
        return fmt;
    }

}
